package it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.emf.ecore.util.EcoreUtil;

import it.univaq.mancoosi.mancoosimm.File;
import it.univaq.mancoosi.mancoosimm.MimeType;
import it.univaq.mancoosi.mancoosimm.MimeTypeHandler;
import it.univaq.mancoosi.injectors.systemconfiguration.managers.FileSystemManager;
import it.univaq.mancoosi.injectors.systemconfiguration.managers.MimeTypeHandlerCacheManager;
import it.univaq.mancoosi.injectors.systemconfiguration.utils.ProcessCommand;

public class UbuntuMimeTypeHandlerCacheManager extends MimeTypeHandlerCacheManager{

	public static MimeTypeHandlerCacheManager getInstance(){
		if (INSTANCE == null)
			INSTANCE = new UbuntuMimeTypeHandlerCacheManager();
		return INSTANCE;
	}

	public void createMimeTypeHandlerCacheFromSystem(){
		String mimeType;
		MimeTypeHandler mth;
		MimeType mt;
		String[] mimeTypeInfo;
		File file;

		System.out.println("Processing MimeTypes....");

//		syncMimeTypeHandlerMap();
//		syncMimeTypeMap();
//
//		if(UbuntuEnvironmentManager.getInstance().getEnvironment().getMimeTypeHandlerCache() != null){
//			this.mimeTypeHandlerCache.getHandlers().addAll(UbuntuEnvironmentManager.getInstance().getEnvironment().getMimeTypeHandlerCache().getHandlers());
//			this.mimeTypeHandlerCache.getMimeTypes().addAll(UbuntuEnvironmentManager.getInstance().getEnvironment().getMimeTypeHandlerCache().getMimeTypes());
//		}

		try {
			String[] cmd1 = {"/bin/sh","-c"," cat /etc/mailcap"};
			BufferedReader input = ProcessCommand.getInstance().getResult(cmd1);	
			
			
//			ArrayList<String> mimeTypeProva = new ArrayList<String>();
//			mimeTypeProva.add("application/vnd.oasis.opendocument.chart; soffice -no-oosplash -calc '%s'; edit=soffice -no-oosplash -calc '%s'; test=test -n \"$DISPLAY\"; description=\"OpenDocument Chart\"; nametemplate=%s.odc");
//			mimeTypeProva.add("text/plain; soffice '%s'; needsterminal");
//			mimeTypeProva.add("application/x-bzpdf; evince '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.pdf.bz2");
//			mimeTypeProva.add("audio/basic; /usr/bin/esdplay '%s'");
//			mimeTypeProva.add("image/x-gzeps; evince '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.eps.gz");
//			
//			Iterator<String> i = mimeTypeProva.iterator();
//			
//			while (i.hasNext() && (mimeType = i.next()) != null) {
			
			while ((mimeType = input.readLine()) != null) {
				mimeTypeInfo = mimeType.split(";");
				
			if ((mimeTypeHandlerMap.get(mimeTypeInfo[0]) == null) &&  ! ( ( mimeTypeInfo[0].startsWith("#")) ||  (mimeTypeInfo[0].isEmpty())) ){
				
//			if ( ! ( ( mimeTypeInfo[0].startsWith("#")) ||  (mimeTypeInfo[0].isEmpty())) ){
//					if(!existsMimeType(mimeTypeInfo[0])){
						mth = factory.createMimeTypeHandler();
						mt = factory.createMimeType();
						mt.setName(mimeTypeInfo[0]);
						mth.setType(mt);
						
						if (!(mimeTypeInfo[1].split(" "))[1].equals("false")) {		// Instead of the executable file, the string false may occur

							file = createHandler((mimeTypeInfo[1].split(" "))[1], mimeTypeInfo[0]);
							if(file != null){
								mth.setHandler(file);
								//update maps
								mimeTypeHandlerMap.put(mimeTypeInfo[0], mth);
								mimeTypeMap.put(mt.getName(), mt);
	
								mimeTypeHandlerCache.getHandlers().add(mth);
								mimeTypeHandlerCache.getMimeTypes().add(mt);
							}
						}
//					}
				}	
			}
			this.mimeTypeHandlerCache.setEnv(UbuntuEnvironmentManager.getInstance().getEnvironment());

			input.close();

		} catch (Exception err) {
			err.printStackTrace();
		}
	}
	
	protected String getHandlerFileNameForMimeType(String mimeTypeName){
		String handlerFileName = "";		
		String[] mimeTypeInfo;
		String mimeType;

		try {
			String[] cmd1 = {"/bin/sh","-c"," cat /etc/mailcap"};
			BufferedReader input = ProcessCommand.getInstance().getResult(cmd1);	
			
			//*****************************************************************
//			ArrayList<String> mimeTypeProva = new ArrayList<String>();
//			mimeTypeProva.add("application/vnd.oasis.opendocument.chart; soffice -no-oosplash -calc '%s'; edit=soffice -no-oosplash -calc '%s'; test=test -n \"$DISPLAY\"; description=\"OpenDocument Chart\"; nametemplate=%s.odc");
//			mimeTypeProva.add("text/plain; soffice '%s'; needsterminal");
//			mimeTypeProva.add("application/x-bzpdf; evince '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.pdf.bz2");
//			mimeTypeProva.add("image/x-gzeps; evince '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.eps.gz");
//			mimeTypeProva.add("audio/basic; /usr/bin/esdplay '%s'");
//			
//			Iterator<String> i = mimeTypeProva.iterator();
//			
//			while (i.hasNext() && (mimeType = i.next()) != null) {

			while ((mimeType = input.readLine()) != null) {
				mimeTypeInfo = mimeType.split(";");

				if ( ! ( ( mimeTypeInfo[0].startsWith("#")) ||  (mimeTypeInfo[0].isEmpty())) && mimeTypeInfo[0].equals(mimeTypeName)){
					if (!(mimeTypeInfo[1].split(" "))[1].equals("false")) {	
						handlerFileName = (mimeTypeInfo[1].split(" "))[1];
					}	    			
				}
			}
		} catch (Exception err) {
			err.printStackTrace();
		}
		return handlerFileName;
		
		
	}
	
	protected File createHandler(String fileName, String mimeTypeName){
		File file = FileSystemManager.getInstance().createFile("");
		try{
			String[] cmd2 = {"/bin/sh","-c"," which " + fileName};
			BufferedReader input = ProcessCommand.getInstance().getResult(cmd2);	
			
			String path = input.readLine();

			if (! (path == null) ) {
				file = FileSystemManager.getInstance().createFile(path);
			}else{
				file = null;
				System.out.println("WARNING: The file \"" + fileName + 
						"\" handling the mime type \"" + mimeTypeName + "\" is missing !");					
			}

		} catch (Exception err) {
			err.printStackTrace();
		}
		return file;
	}

	
	@Override
	public void synchronize() throws IOException {
		createMimeTypeHandlerCacheFromSystem();
	}
	
//	@Override
//	public void synchronize() throws IOException {
//		createMimeTypeHandlerCacheFromSystem();
//		Iterator<MimeType> iterator = this.mimeTypeMap.values().iterator();
//		while (iterator.hasNext()) {
//			MimeType curr = iterator.next();
//			if (!existsMimeTypeInTheSystem(curr.getName())) {
//				this.mimeTypeMap.remove(curr);
//				MimeTypeHandler mth = this.mimeTypeHandlerMap.get(curr.getName());
//				this.mimeTypeHandlerMap.remove(curr.getName());
//				EcoreUtil.delete(curr);
//				EcoreUtil.delete(mth);
//			}else{	
////				String fileName = getHandlerFileNameForMimeType(curr.getName());
////
////				//update mimeTypeHandler in the map
////				MimeTypeHandler handlerToModify = mimeTypeHandlerMap.get(curr.getName());
////				mimeTypeHandlerMap.remove(curr.getName());
////				File handlerFile = createHandler(fileName, curr.getName());
////				handlerToModify.setHandler(handlerFile);
////				mimeTypeHandlerMap.put(curr.getName(), handlerToModify);
////				//update mimeTypeHandler also in the model
////				UbuntuEnvironmentManager.getInstance().getEnvironment().getMimeTypeHandlerCache().getHandlers().get(
////						UbuntuEnvironmentManager.getInstance().getEnvironment().getMimeTypeHandlerCache().getHandlers().indexOf(handlerToModify)).setHandler(handlerFile);
//			}
//		}
//	}

	protected boolean existsMimeTypeInTheSystem(String mimeTypeName){
		boolean result = false;
		String[] mimeTypeInfo;
		String mimeType;
		ArrayList<String> listMimeTypes = new ArrayList<String>();

		try {
			String[] cmd1 = {"/bin/sh","-c"," cat /etc/mailcap"};
			BufferedReader input = ProcessCommand.getInstance().getResult(cmd1);	
			
			//*****************************************************************
//			ArrayList<String> mimeTypeProva = new ArrayList<String>();
//			mimeTypeProva.add("application/vnd.oasis.opendocument.chart; soffice -no-oosplash -calc '%s'; edit=soffice -no-oosplash -calc '%s'; test=test -n \"$DISPLAY\"; description=\"OpenDocument Chart\"; nametemplate=%s.odc");
//			mimeTypeProva.add("text/plain; soffice '%s'; needsterminal");
//			mimeTypeProva.add("application/x-bzpdf; evince '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.pdf.bz2");
//			mimeTypeProva.add("image/x-gzeps; evince '%s'; test=test -n \"$DISPLAY\"; nametemplate=%s.eps.gz");
//			mimeTypeProva.add("audio/basic; /usr/bin/esdplay '%s'");
//			
//			Iterator<String> i = mimeTypeProva.iterator();
//			
//			while (i.hasNext() && (mimeType = i.next()) != null) {

			while ((mimeType = input.readLine()) != null) {
				mimeTypeInfo = mimeType.split(";");

				if ( ! ( ( mimeTypeInfo[0].startsWith("#")) ||  (mimeTypeInfo[0].isEmpty())) ){
					if (!(mimeTypeInfo[1].split(" "))[1].equals("false")) {	
						listMimeTypes.add(mimeTypeInfo[0]);
					}	    			
				}
			}
			Iterator<String> iter = listMimeTypes.iterator();
			while(iter.hasNext() && result != true){
				if((iter.next()).equals(mimeTypeName)){
					result = true;
				}else{
					result = false;
				}
			}

		} catch (Exception err) {
			err.printStackTrace();
		}
		
		return result;
	}

	@Override
	public Boolean existsMimeTypeHandler(String mimeTypeName) {
		return this.mimeTypeHandlerMap.containsKey(mimeTypeName);
	}

	@Override
	public Boolean existsMimeType(String mimeTypeName) {
		return this.mimeTypeMap.containsKey(mimeTypeName);
	}

}
